package com.zzb.ucenter.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zzb.ucenter.mapper.XcCompanyUserMapper;
import com.zzb.ucenter.mapper.XcUserMapper;
import com.zzb.ucenter.mapper.XcUserRoleMapper;
import com.zzb.ucenter.model.dto.AuthParamsDto;
import com.zzb.ucenter.model.dto.XcUserExt;
import com.zzb.ucenter.model.po.XcCompanyUser;
import com.zzb.ucenter.model.po.XcUser;
import com.zzb.ucenter.model.po.XcUserRole;
import com.zzb.ucenter.service.AuthService;
import com.zzb.ucenter.service.WxAuthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.UUID;


/**
 * @Author zzb
 * @Date 2024/6/25 22:02
 * @Version 1.0
 * @description
 */
@Service("wx_authservice")
@Slf4j
public class WxAuthServiceImpl implements AuthService, WxAuthService {

    @Value("${wx.open.app_id}")
    private String appId;
    @Value("${wx.open.app_secret}")
    private String appSecret;
    @Resource
    private RestTemplate restTemplate;
    @Autowired
    private XcUserMapper xcUserMapper;
    @Resource
    private XcUserRoleMapper xcUserRoleMapper;
    @Autowired
    private XcCompanyUserMapper xcCompanyUserMapper;

    @Override
    public XcUserExt execute(AuthParamsDto authParamsDto) {
        //获取用户名
        String username = authParamsDto.getUsername();
        //查询数据库
        XcUser xcUser = xcUserMapper.selectOne(new QueryWrapper<XcUser>().eq("username", username));
        if (xcUser == null) {
            throw new RuntimeException("用户不存在,登录失败");
        }
        XcUserExt xcUserExt = new XcUserExt();
        BeanUtils.copyProperties(xcUser, xcUserExt);
        return xcUserExt;
    }

    @Override
    public XcUserExt wxAuth(String code) {
        //收到code调用微信接口申请access_token
        Map<String, String> accessTokenMap = getWxAccessToken(code);
        //获取用户个人信息
        Map userInfos = getUserInfos(accessTokenMap);
        //保存用户信息到数据库
        XcUser xcUser = addUserToDb(userInfos);
        XcUserExt xcUserExt = new XcUserExt();
        BeanUtils.copyProperties(xcUser, xcUserExt);
        return xcUserExt;
    }

    private XcUser addUserToDb(Map userInfos) {
        //获取unionid
        String unionid = (String) userInfos.get("unionid");
        //根据unionid查询
        XcUser xcUser = xcUserMapper.selectOne(new QueryWrapper<XcUser>().eq("wx_union_id", unionid));
        if (xcUser != null) {
            return xcUser;
        }
        //获取nickname
        String nickname = (String) userInfos.get("nickname");
        //获取sex
        int sex = (int) userInfos.get("sex");
        //获取用户头像
        String headimgurl = (String) userInfos.get("headimgurl");
        xcUser = new XcUser();
        xcUser.setWxUnionId(unionid);
        xcUser.setNickname(nickname);
        xcUser.setUsername(nickname);
        xcUser.setName(nickname);
        xcUser.setUserPicture(headimgurl);
        xcUser.setSex(Integer.toString(sex));
        xcUser.setCreateTime(LocalDateTime.now());
        xcUser.setStatus("1");
        xcUserMapper.insert(xcUser);
        //查询是否关联机构
        XcCompanyUser xcCompanyUser = xcCompanyUserMapper.selectOne(new LambdaQueryWrapper<XcCompanyUser>().eq(XcCompanyUser::getUserId, xcUser.getId()));
        if (xcCompanyUser != null) {
            xcUser.setCompanyId(xcCompanyUser.getCompanyId());
        }
        //向用户角色关系表新增数据
        XcUserRole xcUserRole = new XcUserRole();
        xcUserRole.setId(UUID.randomUUID().toString());
        xcUserRole.setUserId(xcUser.getId());
        xcUserRole.setRoleId("17");
        xcUserRole.setCreateTime(LocalDateTime.now());
        xcUserRoleMapper.insert(xcUserRole);
        return xcUser;
    }

    private Map getUserInfos(Map<String, String> accessTokenMap) {
        //获取access_token
        String accessToken = accessTokenMap.get("access_token");
        //获取openid
        String openid = accessTokenMap.get("openid");
        //http请求方式: GET
        String urlTemplate = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s";
        String url = String.format(urlTemplate, accessToken, openid);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, null, String.class);
        String userInfo = response.getBody();
        Map userInfoMap = JSON.parseObject(userInfo, Map.class);
        return userInfoMap;
    }

    private Map<String, String> getWxAccessToken(String code) {
        // 1. 请求路径模板，参数用%s占位符
        String url_template = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";
        // 2. 填充占位符：appid，secret，code
        String url = String.format(url_template, appId, appSecret, code);
        // 3. 远程调用URL，POST方式（详情参阅官方文档）
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, null, String.class);
        // 4. 获取相应结果，响应结果为json格式
        String result = exchange.getBody();
        // 5. 转为map
        Map<String, String> map = JSON.parseObject(result, Map.class);
        return map;
    }


}
